package com.erongdu.wireless.tools.utils;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.erongdu.wireless.tools.R;

/**
 * Author: TinhoXu
 * E-mail: xth@erongdu.com
 * Date: 2016/8/23 17:57
 * <p/>
 * Description: Toast工具类
 */
@SuppressWarnings("unused")
public class ToastUtil {
    /**
     * 禁止重复提示
     */
    private static final long Interval = 3 * 1000;
    /**
     * 消息软引用
     */
    private static final SoftHashMap<String, Long> map = new SoftHashMap<>();
    /**
     * Toast 对象
     */
    private static Toast toast;

    public static void toast(String msg) {
        toast(ContextHolder.getContext(), msg);
    }

    public static void toast(int id) {
        toast(ContextHolder.getContext(), ContextHolder.getContext().getString(id));
    }

    private static void toast(Context context, String msg) {
        if (!TextUtils.isEmpty(msg)) {
            long preTime = 0;
            if (map.containsKey(msg)) {
                preTime = map.get(msg);
            }
            final long now = System.currentTimeMillis();
            if (now >= preTime + Interval) {
                if (toast != null) {
                    toast.cancel();
                }
                if (context != null) {
                    Toast toast = Toast.makeText(context, null, Toast.LENGTH_SHORT);
                    toast.setText(msg);
                    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                    toast.show();
                    map.put(msg, now);
                    ToastUtil.toast = toast;
                }
            }
        }
    }


    public static void toastView(Context context, int layoutId, String msg, int iv) {
        TextView mTextView;
        ImageView imageView;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //自定义布局
        View view = inflater.inflate(layoutId, null);
        //自定义toast文本
        mTextView = view.findViewById(R.id.toast_msg);
        mTextView.setText(msg);
        if (iv != 0) {//有没有图片
            imageView = view.findViewById(R.id.toast_iv);
            imageView.setImageResource(iv);
        }
        if (toast == null) {
            toast = new Toast(context);
        }
        //设置toast居中显示
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(view);
        toast.show();
    }


}
